<template>
  <div id="category">
    <!-- 栏目管理的头部——添加和搜索 -->
    <div id="category-header">
      <el-button type="primary" @click="addcategory">添加</el-button>
      <el-input v-model="input" placeholder="请输入栏目名称" clearable />
      <el-button type="primary" icon="el-icon-search" @click="search">查找</el-button>
    </div>
    <!-- 栏目管理的数据展示 -->
    <div id="category-main">
      <el-table
        :data="categories"
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="编号"
          width="180"
          align="center"
        />
        <el-table-column
          prop="name"
          label="栏目名称"
          width="180"
          align="center"
        />
        <el-table-column
          prop="num"
          label="序号"
          width="180"
          align="center"
        />
        <el-table-column
          prop="parentId"
          label="父栏目"
          width="180"
          align="center"
        />
        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="deletecategory(scope.row.id)">删除</el-button>
            <el-button type="text" @click="editorCategory(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="category-footer">
      <!-- 栏目管理的分页 -->
      <div class="block">
        <el-pagination
          :current-page.sync="currentPage1"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑的模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="myform" :model="form" :rules="rules">
        <el-form-item label="栏目名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入栏目名称" />
        </el-form-item>
        <el-form-item label="序号" :label-width="formLabelWidth" prop="num">
          <el-input v-model="form.num" autocomplete="off" placeholder="请输入序号" />
        </el-form-item>
        <el-form-item label="所属栏目" :label-width="formLabelWidth">
          <el-select v-model="form.parentId" placeholder="请选择所属栏目">
            <el-option v-for="item in categories" :key="item.id" :label="item.parentId" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('myform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'querystring'

export default {
  data() {
    return {
      input: '',
      categories: [],
      currentPage1: 1,
      pageSize: 6,
      total: 0,
      // 模态框
      title: '添加栏目信息',
      dialogFormVisible: false,
      form: {
        name: '',
        num: '',
        parentId: '',
        delivery: false,
        type: []
      },
      formLabelWidth: '120px',
      rules: {
        name: [
          { required: true, message: '请输入栏目名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入序号', trigger: 'blur' },
          { min: 1, max: 99999, message: '长度在 1 到 99999 个字符', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择所属栏目', trigger: 'change' }
        ]
      }
    }
  },

  computed: {
  },
  created() {
    this.findallCategory()
  },

  methods: {
    // 给编辑按钮绑定事件
    editorCategory(row) {
      this.dialogFormVisible = true
      this.title = '编辑栏目信息'
      this.form = {
        name: row.name,
        num: row.num,
        parentId: row.parentId
      }
    },

    // 给删除按钮绑定事件
    deletecategory(id) {
      var self = this
      var id = id
      // console.log(id);
      // 显示弹框
      this.$confirm('此操作将永久删除该条信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //  发送异步请求
        this.$axios.get('/category/deleteById', { params: { id }}).then(response => {
          if (response.data.status == 200) {
            // console.log('成功');
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            self.findallCategory()
          } else {
            // console.log(response.data);
            this.$message.error('错了哦，删除失败了')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 给查询按钮绑定事件
    search() {
      if (this.input) {
        this.findallCategory(this.input)
      } else {
        this.findallCategory()
      }
    },

    // 给模态框确定按钮绑定事件
    submitForm(formName) {
      var self = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          self.$axios.post('/category/saveOrUpdate', qs.stringify(self.form)).then(response => {
            if (response.data.status == 200) {
              // console.log(response.data.message);
              this.$message({
                showClose: true,
                message: '恭喜您，成功添加了一条消息',
                type: 'success'
              })
              self.findallCategory()
            } else {
              this.$message({
                showClose: true,
                message: '错了哦，这个数据添加失败了',
                type: 'error'
              })
            }
            self.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 给添加按钮绑定事件
    addcategory() {
      // 打开模态框
      this.dialogFormVisible = true
      this.title = '添加栏目信息'
      this.form = {}
    },

    // 封装分页请求栏目信息
    findallCategory(name) {
      if (name) {
        var data = {
          page: this.currentPage1,
          pageSize: this.pageSize,
          name: name
        }
      } else {
        var data = {
          page: this.currentPage1,
          pageSize: this.pageSize
        }
      }

      // 发送异步请求
      this.$axios.post('/category/query', qs.stringify(data)).then(response => {
        console.log(response.data)
        this.total = response.data.data.total
        this.categories = response.data.data.list
      })
    },

    //  分页按钮
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.currentPage1 = val
      this.findallCategory()
    }
  }

}
</script>
<style lang='scss' scoped>
#category{
  padding: 20px;
  #category-header .el-input{
    width: 25%;
    margin-left: 20px;
  }
  #category-header :nth-child(3){
    margin-left: 15px;
  }
  #category-main{
    line-height: 50px;
  }
}
</style>
